﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading;

namespace BL
{
    public class cTCPConnectionHandler : cConnectionHandler
    {
        TcpListener m_Listener;
        public TcpListener Listener
        {
            get { return m_Listener; }
            set { m_Listener = value; }
        }

        TcpClient m_Client;
        public TcpClient Client
        {
            get { return m_Client; }
            set { m_Client = value; }
        }

        public override void StartListening(int port)
        {
            Listener = new TcpListener(IPAddress.Any, port);
            Listener.Start();
            int timeout = 0;
            while ((!Listener.Pending()) && (timeout < 60))
            {
                timeout++;
                Thread.Sleep(1000);
            }
            if (Listener.Pending())
                Client = Listener.AcceptTcpClient();
            Listener.Stop();
        }

        public void SendData(byte[] data)
        {
            if (Client.Connected)
            {
                NetworkStream stream = Client.GetStream();
                stream.Write(data, 0, data.Count());
                stream.Flush();
            }
        }

        public byte[] ReceiveData()
        {
            int i;
            byte[] dataReceived = null;
            while (Client.Connected && Client.Available > 0)
            {
                NetworkStream stream = Client.GetStream();
                byte[] dataReader = new byte[Client.Available];
                if (dataReceived == null)
                    dataReceived = new byte[0];
                byte[] temp = dataReceived;
                i = stream.Read(dataReader, 0, Client.Available);
                dataReceived = new byte[temp.LongLength + dataReader.LongLength];
                temp.CopyTo(dataReceived, 0);
                dataReader.CopyTo(dataReceived, temp.Length);
            }
            return dataReceived;
        }

        public override bool Connect(string IP, int port)
        {
            try
            {
                Client = new TcpClient(IP, port);
                if (Client.Connected)
                    return true;
            }
            catch (SocketException)
            {
                //Do nothing
            }
            return false;
        }

        public override void Disconnect()
        {
            Client.Close();
        }
    }
}
